package com.chj.comp.service.demo1.listener.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.chj.comp.common.rabbitmq.message.MessageEntity;
import com.chj.comp.common.rabbitmq.queue.MqTopicQueue;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
@RabbitListener(queues = MqTopicQueue.QUEUE_NAME1, ackMode = "MANUAL")
public class MqTopic1Listener {

    // isDefault-不管生产者生产哪种类型的消息，消费者设置默认处理
    @RabbitHandler(isDefault = true)
    public void handleMessage(Message message,
                              Channel channel,
                              @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException, InterruptedException {
        // 确认收到消息(确认后，生产者不在重复发送)
        // false 当前消费者确认收到，true 所有消费者确认收到
        channel.basicAck(deliveryTag, false);

        String messageId = message.getMessageProperties().getMessageId();
        MessageEntity messageEntity = JSON.parseObject(message.getBody(), MessageEntity.class);
        log.info("消费消息（主题类型1）-->{}:{}", messageId, messageEntity.getName());

        // @TODO
        // 消息消费完成后，将消息状态改为已消费

        Thread.sleep(3000);
    }
}
